package com.example.pkmedical.Activity.weight.history;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.pkmedical.Base.BaseActivity;
import com.example.pkmedical.DB.WeightData;
import com.example.pkmedical.DB.WeightData_Table;
import com.example.pkmedical.R;
import com.example.pkmedical.Utils.SPUtils;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.ModelAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class WeightLineChartActivity extends BaseActivity {


    @BindView(R.id.main_house)
    ImageView mainHouse;
    @BindView(R.id.main_house_text)
    TextView mainHouseText;
    @BindView(R.id.weightlinechart)
    LineChartView weightlinechart;

    String[] dataY;//Y轴的标注
    @BindView(R.id.weight_history_back_button)
    Button weightHistoryBackButton;
    @BindView(R.id.standard_weight)
    TextView standardWeight;
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
    String[] array = {"", "", "", "", "", ""};
    float[] weightarray = {0f, 0f, 0f, 0f, 0f, 0f};
    float[] weightarrayTWO = {0f, 0f, 0f, 0f, 0f, 0f};
//    float[] weightarray;
//    float[] weightarrayTWO;
    int max;
    int min;
    long needDelId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_myweight_history);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        mainHouse.setImageResource(R.drawable.img_title_weight);
        mainHouseText.setText(R.string.title_weight);
        makeData();
        initAxisXLables();//获取x轴的标注
        initAxisPoints();//获取坐标点
        initLineChart();//初始化

    }

    /**
     * 设置X 轴的显示
     */
    private void initAxisXLables() {
        for (int i = 0; i < array.length; i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(array[i]));
        }
    }

    /**
     * 图表的每个点的显示
     */
    private void initAxisPoints() {
        for (int i = 0; i < weightarray.length; i++) {
            mPointValues.add(new PointValue(i, weightarray[i]));
        }
    }

    /**
     * 图表的绘制
     */
    private void initLineChart() {
        Line line = new Line(mPointValues).setColor(getResources().getColor(R.color.green_text));  //折线的颜色
        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.SQUARE）
        line.setCubic(true);//曲线是否平
//     line.setStrokeWidth(3);//线条的粗细，默认是3
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
        line.setFormatter(new SimpleLineChartValueFormatter(1));//设置显示小数点
// line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
        line.setStrokeWidth(3);
        line.setPointRadius(10);
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setValueLabelBackgroundColor(Color.TRANSPARENT);
        data.setValueLabelBackgroundAuto(true);
        data.setValueLabelBackgroundEnabled(true);
        data.setValueLabelTextSize(20);
        data.setValueLabelsTextColor(Color.WHITE);  //此处设置坐标点旁边的文字颜色
        data.setLines(lines);


        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(getResources().getColor(R.color.green_back_text));//灰色


        axisX.setTextSize(18);//设置字体大小
        axisX.setMaxLabelChars(0); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        axisX.setHasLines(false); //x 轴分割线


        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setTextSize(20);//设置字体大小
        axisY.setTextColor(getResources().getColor(R.color.green_back_text));
        axisY.setHasLines(true);
        axisY.setMaxLabelChars(11);//max label length, for example 60
        axisY.setLineColor(getResources().getColor(R.color.color_help_text));
        // 这样添加y轴坐标 就可以固定y轴的数据
        List<AxisValue> values = new ArrayList<>();
        for (int i = 0; i < dataY.length; i++) {
            AxisValue value = new AxisValue(Integer.parseInt(dataY[i]));
            values.add(value);
        }
        axisY.setValues(values);
        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //y轴设置在右边

        //设置行为属性，支持缩放、滑动以及平移

        weightlinechart.setInteractive(false);
        weightlinechart.setZoomType(ZoomType.HORIZONTAL);
        weightlinechart.setMaxZoom((float) 1);//最大放大比例
        weightlinechart.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        weightlinechart.setLineChartData(data);
        weightlinechart.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
        Viewport v = new Viewport(weightlinechart.getMaximumViewport());
        v.left = 0;
        v.right = 6;
        weightlinechart.setCurrentViewport(v);
        resetViewport();
    }

    /**
     * 重点方法，计算绘制图表
     */
    private void resetViewport() {
        //创建一个图标视图 大小为控件的最大大小
        final Viewport v = new Viewport(weightlinechart.getMaximumViewport());
        v.left = 0;                             //坐标原点在左下
        v.bottom = min;
        v.top = max;                            //最高点为100
        v.right = 6;           //右边为点 坐标从0开始 点号从1 需要 -1
        weightlinechart.setMaximumViewport(v);   //给最大的视图设置 相当于原图
        weightlinechart.setCurrentViewport(v);   //给当前的视图设置 相当于当前展示的图
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void showDialog(String... msg) {

    }

    private void makeData() {
        WeightData weightData = new WeightData();
        ModelAdapter<WeightData> adapter = FlowManager.getModelAdapter(WeightData.class);
        List<WeightData> list = SQLite.select().from(WeightData.class).queryList();
        if (list.size() > 6) {
            needDelId = list.get(0).id;
            //方法二 直接删除
            SQLite.delete(WeightData.class)
                    .where(WeightData_Table.id.eq(needDelId))
                    .execute();
        } else {

        }
        //查询
        List<WeightData> list1 = SQLite.select().from(WeightData.class).queryList();

        //使用for循环得到数组
        if (list1.size() >= 6) {
            for (int i = 0; i < 6; i++) {
                array[i] = list1.get(i).date;
                weightarray[i] = list1.get(i).weight;
                weightarrayTWO[i] = list1.get(i).weight;
                Log.d("yangshuo", array + "");
            }
        } else {
            for (int i = 0; i < list1.size(); i++) {
                array[i] = list1.get(i).date;
                weightarray[i] = list1.get(i).weight;
                weightarrayTWO[i] = list1.get(i).weight;
                Log.d("yangshuo", array + "");
            }

        }
        min = (int) BubbleSort(weightarrayTWO)[0];
        max = (int) BubbleSort(weightarrayTWO)[5];
        max += 5;
        min -= 5;
        List<String> mLeftList = new ArrayList<>();
        for (int i = min; i < max; i++) {
            mLeftList.add(i + "");
        }
        dataY = new String[mLeftList.size()];
        mLeftList.toArray(dataY);

//        DecimalFormat decimalFormat = new DecimalFormat("00.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        if (!SPUtils.getInstance().getString("user_first_weight").equals("不适用")) {
            standardWeight.setText("初始体重：" + SPUtils.getInstance().getString("user_first_weight"));
        } else {
            standardWeight.setText("初始体重：不适用");
        }
    }

    /**
     * 冒泡排序：两个数比较大小，较大的数下沉，较小的数冒出来
     */
    private float[] BubbleSort(float[] bubbleArray) {
        for (int i = 0; i < bubbleArray.length - 1; i++) {
            for (int j = 0; j < bubbleArray.length - i - 1; j++) {
                //交换位置
                if (bubbleArray[j] > bubbleArray[j + 1]) {
                    float temp = bubbleArray[j];
                    bubbleArray[j] = bubbleArray[j + 1];
                    bubbleArray[j + 1] = temp;
                }
            }
        }
        return bubbleArray;
    }

    @OnClick(R.id.weight_history_back_button)
    public void onViewClicked() {
        WeightLineChartActivity.this.finish();
    }
}
